<template>
  <div class="order-management">
    <el-card>
      <!-- 操作栏 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">

        <el-form-item label="货架规格">
          <el-input v-model="searchForm.specifications" placeholder="请输入货架规格"></el-input>
        </el-form-item>

        <el-form-item label="所在仓库">
          <el-input v-model="searchForm.warehouseName" placeholder="请输入所在仓库"></el-input>
        </el-form-item>

        <el-form-item label="仓库状态">
          <el-select v-model="searchForm.status">
            <el-option
              v-for="status in shelvesStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDeleteBatch">批量删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="uploadExcelDialog=true">导入</el-button>
          <el-button type="primary"  @click="downloadExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>


    <!-- 数据展示层 -->
    <el-table :data="tableData" border
              style="width: 100%"
              @selection-change="handleSelectionChange"
              @row-click="handleEdit">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="shelfId" label="货架ID" />
      <el-table-column prop="specifications" label="规格" />
      <el-table-column prop="warehouseName" label="仓库名称" />
      <el-table-column prop="zone" label="区域" />
      <el-table-column prop="number" label="编号" />
      <el-table-column prop="capacity" label="容量" />
      <el-table-column prop="remarks" label="备注" />
      <el-table-column prop="status" label="状态" />
      <el-table-column prop="createTime" label="创建时间" />
    </el-table>


    <!-- 新增/修改表单 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="60%">
      <el-form :model="EditForm" :rules="rules" ref="EditForm" label-width="100px">
        <el-form-item label="货架ID" prop="shelfId">
          <el-input v-model.number="EditForm.shelfId" placeholder="请输入货架ID" :disabled="title === '修改'"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="EditForm.specifications" placeholder="请输入规格"></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="EditForm.warehouseName" placeholder="请输入仓库名称"></el-input>
        </el-form-item>
        <el-form-item label="区域" prop="zone">
          <el-input v-model="EditForm.zone" placeholder="请输入区域"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="number">
          <el-input v-model="EditForm.number" placeholder="请输入编号"></el-input>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input v-model.number="EditForm.capacity" placeholder="请输入容量"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="EditForm.remarks" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="EditForm.status" placeholder="请选择状态">
            <el-option
              v-for="status in shelvesStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onClose">关 闭</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 文件上传弹窗 -->
    <el-dialog title="上传文件" :visible.sync="uploadExcelDialog" width="30%">
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="uploadExcelFun"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>

        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>

        <el-button type="primary" @click="">确 定</el-button>

      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15]"
      :page-size="queryPage.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
    />



  </div>
</template>

<script>
import {findAllByPage,deleteBtach,add,update,uploadExcel} from '@/api/base/baseShelves'
export default {
  name: 'orderPlatform',
  data() {
    return {
      uploadExcelDialog:false,
      file: null,
      fileList: [],
      shelvesStatusOptions: [
        { value: '正常', label: '正常' },
        { value: '禁用', label: '禁用' }
      ],
      searchForm: {},
      queryPage: {
        pageNum: 1,
        pageSize: 5
      },
      tableData: [],
      currentPage: 1,
      total: 0,
      title: '',
      dialogVisible: false,
      EditForm: {
        shelfId: null,
        specifications: '',
        warehouseName: '',
        zone: '',
        number: '',
        capacity: null,
        remarks: '',
        status: ''
      },
      rules: {
        shelfId: [
          { required: true, message: '货架ID不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字类型', trigger: 'blur' }
        ],
        specifications: [
          { required: true, message: '规格不能为空', trigger: 'blur' }
        ],
        warehouseName: [
          { required: true, message: '仓库名称不能为空', trigger: 'blur' }
        ],
        zone: [
          { required: true, message: '区域不能为空', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '编号不能为空', trigger: 'blur' }
        ],
        capacity: [
          { required: true, message: '容量不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字类型', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      },
      multipleSelection: []
    }
  },
  created() {
    this.loadData();
  },

  methods: {
    downloadExcel(){
      this.$confirm(`确定要下载Excel吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href="http://localhost:8888/base/shelves/download/excel"
        this.$message({
          message: '下载成功!',
          type: 'success',
          duration: 1200
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下载'
        });
      });
    },
    beforeUpload(){
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      return true;
    },
    uploadExcelFun() {
      const file = this.file;
      const formData = new FormData();
      formData.append('file', file);
      //封装文件上传的方法
      uploadExcel(formData).then(res => {
        if (res.code === 20000) {
          this.$message.success('上传成功');
          //上传成功后添加到文件列表
          this.fileList.push({
            name: file.name,
          });
          this.uploadExcelDialog = false;
          this.pageNum = 1;
          this.loadData()
        } else {
          this.$message.error(res.message || '上传失败');
        }
      })
    },
    handleChange(file) {
      this.file = file.raw;
    },
    // 关闭
    onClose() {
      this.dialogVisible = false
      this.EditForm = {}
      this.handleReset()

    },
    // 批量删除
    handleDeleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('此操作将永久删除选中的文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        // distinguishCancelAndClose: true,    // 重要，设置为true才会把右上角X和取消区分开来
        // closeOnClickModal: false
      }).then(() => {// 用户点击确定进入此流程
        const ids = this.multipleSelection.join(',')
        deleteBtach(ids)
          .then(ret => {
            if (ret.code === 20000) {
              this.$message.success('批量删除成功')
              this.queryPage.pageNum = 1
              this.loadData()
            } else {
              this.$message.error(ret.message || '删除失败')
            }
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    //select方法监控
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.shelfId)
    },
    // 新增/修改表单的提交
    onSubmit() {
      this.$refs.EditForm.validate(valid => {
        if (!valid) {
          this.$message.error('请正确填写表单')
          return
        }
        if (this.title === '新增') {
          console.log('新增')
          add(this.EditForm).then(res => {
            if (res.code == 20000) {
              this.$message.success('添加成功！');
              this.dialogVisible = false;
              this.loadData();
              this.EditForm = {}
            } else {
              this.$message.error('添加失败！');
            }
          })
        }
        if (this.title === '修改') {
          console.log('修改')
          update(this.EditForm).then(res => {
            if (res.code == 20000) {
              this.$message.success('修改成功！');
              this.dialogVisible = false;
              this.loadData();
              this.EditForm = {}
            } else {
              this.$message.error('修改失败！');
            }
          })
        }
      })
    },

    //分页-页码大小改变
    handleSizeChange(newSize) {
      this.queryPage.pageSize = newSize
      this.loadData()
    },
    //分页-当前页码数改变
    handleCurrentChange(page) {
      this.queryPage.pageNum = page;
      this.loadData();
    },
    // 加载数据
    loadData() {
      findAllByPage(this.queryPage).then(res => {
        if (res.code == 20000) {
          console.log(res)
          this.tableData = res.data.list;
          this.total = res.data.total
        } else {
          this.$message.error(res.message);
        }
      })
    },
    //查询
    handleSearch() {
      // 构建查询参数
      const params = {
        ...this.searchForm,
        createTime: undefined
      };

      // 重置分页
      this.queryPage.pageNum = 1;
      this.queryPage.pageSize = 5;

      // 处理时间范围
      if (this.searchForm.createTime?.length === 2) {
        params.startDate = this.searchForm.createTime[0];
        params.endDate = this.searchForm.createTime[1];
      }
      // 合并查询参数和分页参数，然后交给loadData
      this.queryPage = { ...this.queryPage, ...params };

      // 加载数据
      this.loadData();
    },
    //重置
    handleReset() {
      this.searchForm = {};
      this.queryPage = { pageNum: 1, pageSize: 5 };
      this.loadData();
      this.$refs.EditForm.resetFields();
    },
    handleAdd() {
      this.title = '新增'
      this.dialogVisible = true;
      this.EditForm = {};
    },
    handleEdit(row) {
      this.title = '修改';
      this.dialogVisible = true;
      this.EditForm = row;
    },

  },
  watch: {

  },
}
</script>


<style scoped lang="scss">
.order-management {
  padding: 20px；
}
</style>
